<template>
  <view class="notice-bar" :class="{ 'is-scrolling': isScrolling }">
    <view class="notice-content" ref="content">
      <text class="notice-icon">📢</text>
      <text class="notice-text" :style="{animation:textStyle.animation}" ref="text">{{ text }}</text>
    </view>
  </view>
</template>

<script>
export default {
  name: 'NoticeBar',
  props: {
    text: {
      type: String,
      default: 'مۇھىم ئۇقتۇرۇش'
    },
    speed: {
      type: Number,
      default: 50
    },
    color: {
      type: String,
      default: '#f56c6c'
    },
    backgroundColor: {
      type: String,
      default: '#fff7e6'
    }
  },
  data() {
    return {
      isScrolling: false,
      textWidth: 0,
      containerWidth: 0,
      textStyle: {}
    }
  },
  mounted() {
    this.initSize()
  },
  methods: {
    async initSize() {
      // 获取容器宽度
      const query = uni.createSelectorQuery().in(this)
      query.select('.notice-content').boundingClientRect(data => {
        this.containerWidth = data.width
      }).exec()

      // 获取文本宽度
      query.select('.notice-text').boundingClientRect(data => {
        this.textWidth = data.width
        if (this.textWidth > this.containerWidth) {
          this.isScrolling = true
          this.textStyle = {
            animation: `${this.textWidth / this.speed}s`
          }
        }
      }).exec()
    }
  }
}
</script>

<style scoped>
.notice-bar {
  background-color: #fff7e6;
  padding: 16rpx 24rpx;
  overflow: hidden;
}

.notice-content {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.notice-icon {
  margin-right: 16rpx;
}

.notice-text {
  color: #f56c6c;
  font-size: 28rpx;
  white-space: nowrap;
}

.is-scrolling .notice-text {
  animation: scroll linear infinite;
}

@keyframes scroll {
  0% {
    transform: translateX(100%);
  }
  100% {
    transform: translateX(-100%);
  }
}
</style>